package com.codebattery.service;

import com.codebattery.repository.Credentials;
import com.codebattery.repository.CredentialsDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class JdbcUserDetails implements UserDetailsService {

    @Resource
    private CredentialsDao credentialDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Credentials credentials = credentialDao.selectByName(username);

        if (credentials == null) {
            throw new UsernameNotFoundException("用户 '" + username + "' 未找到");
        }

        return new User(
                credentials.getName(),
                credentials.getPassword(),
                credentials.getEnabled(),
                true,
                true,
                true,
                credentials.getAuthorities());
    }

}